package com.imist.nettybasic4.server.handler;

import com.imist.nettybasic4.protocol.request.QuitGroupRequestPacket;
import com.imist.nettybasic4.protocol.response.QuitGroupResponsePacket;
import com.imist.nettybasic4.utils.SessionUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
@ChannelHandler.Sharable
public class QuitGroupRequestHandler extends SimpleChannelInboundHandler<QuitGroupRequestPacket> {

    public static final QuitGroupRequestHandler INSTANCE = new QuitGroupRequestHandler();

    protected QuitGroupRequestHandler() {
    }
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, QuitGroupRequestPacket quitGroupRequestPacket) throws Exception {
        //1 . 获取群对应的channelGroup,然后将当前channel移除
        String groupId = quitGroupRequestPacket.getGroupId();
        ChannelGroup channels = SessionUtils.getChannelGroup(groupId);
        channels.remove(channelHandlerContext.channel());
        // 2. 构造退群响应发送给客户端
        QuitGroupResponsePacket quitGroupResponsePacket = new QuitGroupResponsePacket();
        quitGroupResponsePacket.setGroupId(quitGroupRequestPacket.getGroupId());
        quitGroupResponsePacket.setSuccess(true);
        channelHandlerContext.writeAndFlush(quitGroupResponsePacket);
    }
}
